package auth

import (
	"context"
	"github.com/golang-jwt/jwt/v4"
	"internal/store/redis"
	"internal/util"
	"strconv"
	"time"
)

const pSecretKey = "ZhangSanNiuBiDiHen,o!"

type CustomClaims struct {
	jwt.RegisteredClaims
	UserId  int64 `json:"user_id"`
	IsAdmin bool  `json:"is_admin"`
}

func GenerateToken(Userid int64, IsAdmin bool) (string, error) {
	ctx := context.Background()
	token, err := redis.GetRedisConn().Get(ctx, strconv.FormatInt(Userid, 10)).Result()
	if err != nil {
		claims := CustomClaims{
			RegisteredClaims: jwt.RegisteredClaims{
				ExpiresAt: jwt.NewNumericDate(time.Now().Add(5 * time.Minute)),
				Issuer:    "itmActivity",
			},
			UserId:  Userid,
			IsAdmin: IsAdmin,
		}
		token, err = jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(pSecretKey))
		if err != nil {
			return "", err
		}
		err := redis.GetRedisConn().Set(ctx, strconv.FormatInt(Userid, 10), token, time.Minute*5).Err()
		if err != nil {
			util.LogSrv.Error("[redis] key=%d,value=%s, err=%v", Userid, token, err)
		}
	}
	return token, nil
}
